package com.beiding.jsonanalyzer.querylink;

import com.beiding.jsonanalyzer.analyze.select.Selector;
import com.beiding.jsonanalyzer.analyze.select.SelectorBuilder;
import com.beiding.jsonanalyzer.flow.BranchNode;
import com.beiding.jsonanalyzer.flow.ValueNode;
import com.beiding.jsonanalyzer.flow.flowevents.BatchEndEvent;
import com.beiding.jsonanalyzer.flow.flowevents.BatchStartEvent;
import com.beiding.jsonanalyzer.flow.flowevents.DataNodeEvent;

public class SelectQueryLinkNode<W extends ValueNode> extends ComputeNode<W> {


    private SelectorBuilder selectorBuilder;

    public SelectQueryLinkNode(QueryLinkNode<W> pre, SelectorBuilder selectorBuilder) {
        super(pre);
        this.selectorBuilder = selectorBuilder;

    }

    @Override
    protected void bindByComputeNode(BranchNode<W> preResult, BranchNode<W> newBranchNode) {

        Selector selector = selectorBuilder.build();

        if (selector.isAgg()) {
            ComputeNodeUtils.bindBaseEvent(preResult, newBranchNode);

            preResult.onDataEvent(BatchStartEvent.eventType(), event -> {
                //流开始 重置聚合
                selector.resetAgg();
                newBranchNode.signDataEvent(event);
            });
            preResult.onDataEvent(DataNodeEvent.eventType(), event -> {
                //放入聚合批
                selector.pugAgg(event.getData());
            });
            preResult.onDataEvent(BatchEndEvent.eventType(), event -> {
                //产生批结果
                W w = selector.aggGet(preResult.getBranch().getValueNodeFactory());
                newBranchNode.signDataEvent(new DataNodeEvent<>(w));
            });

        } else {
            //如果不是聚合的,则采用简单的处理方式
            ComputeNodeUtils.bindControlEvent(preResult, newBranchNode);
            preResult.onDataEvent(DataNodeEvent.eventType(), event -> {
                W w = selector.executeOne(event.getData(), preResult.getBranch().getValueNodeFactory());
                newBranchNode.signDataEvent(new DataNodeEvent<>(w));
            });
        }

    }
}
